package com.szpt.mo.bhubackground.controller;

import com.alibaba.druid.util.StringUtils;
import com.szpt.mo.bhubackground.entity.TbPost;
import com.szpt.mo.bhubackground.entity.TbUser;
import com.szpt.mo.bhubackground.entity.parameters.R_Pager;
import com.szpt.mo.bhubackground.service.ITbPostService;
import com.szpt.mo.bhubackground.service.ITbUserService;
import com.szpt.mo.bhubackground.util.config.StatusCheckUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

import com.szpt.mo.bhubackground.entity.parameters.R_Result;
import com.szpt.mo.bhubackground.util.config.JWTUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import javax.servlet.http.HttpServletRequest;


/**
 * @Package: com.szpt.mo.bhubackground.entity.TbPost
 * @Description: <前端控制器>
 * @Author: mo
 * @CreateDate: 2022-06-06
 * @UpdateUser: mo
 * @UpdateDate: 2022-06-06
 * @UpdateRemark: <>
 * @Version: 1.0
 */
@RestController
@Api(tags = "TbPost-相关接口")
@RequestMapping(value = "TbPost")
public class TbPostController {

    private static final Logger logger = LoggerFactory.getLogger(TbPostController.class);

    @Autowired
    private ITbPostService service;
    @Autowired
    private ITbUserService userService;

    @GetMapping("{id}")
    @ApiOperation(value = "获取某一实体")
    @ResponseBody
    public R_Result<TbPost> getITbPostServiceDetails(@PathVariable Long id) {
        System.out.println(id);
        TbPost byId = service.getById(id);
        TbUser user = userService.getById(byId.getUserId());
        byId.setUser(user);
        return new R_Result<>(byId, "获取成功！", 200);
    }

    @PostMapping
    @ApiOperation(value = "新增数据")
    @ResponseBody
    public boolean saveITbPostService(@RequestBody TbPost dto,HttpServletRequest request) {
        TbUser login = StatusCheckUtils.isLogin(request);
        if (null == login) {
            return false;
        }
        dto.setUserId(login.getId());
        return service.save(dto);
    }

    @PutMapping("{id}")
    @ApiOperation(value = "修改数据")
    @ResponseBody
    public R_Result<Boolean> modifyITbPostService(HttpServletRequest request,@RequestBody TbPost dto, @PathVariable Long id) {
        boolean success = false;

        TbUser login = StatusCheckUtils.isLogin(request);
        if (null == login) {

            return new R_Result<>(success, success ? "成功" : "失败", success ? 200 : 500);

        }
        dto.setUserId(login.getId());
        dto.setId(id);
        success =  service.updateById(dto);
        return new R_Result<>(success, success ? "成功" : "失败", success ? 200 : 500);
    }

//    @DeleteMapping("batch")
//    @ApiOperation(value = "批量删除数据")
//    @ResponseBody
//    public boolean batchRemoveITbPostService(@RequestParam(value = "ids") List<Long> ids) {
//        return service.removeByIds(ids);
//    }

    @DeleteMapping("{id}")
    @ApiOperation(value = "删除数据")
    @ResponseBody
    public boolean removeITbPostService(@PathVariable Long id) {
        return service.removeById(id);
    }


    @GetMapping("/getList/{current}/{size}/{total}")
    @ApiOperation(value = " 获取列表数据")
    @ResponseBody
    public R_Result<R_Pager<TbPost>> getTbPost(HttpServletRequest request, @PathVariable Integer current, @PathVariable Integer size, @PathVariable Integer total) {

        boolean save = false;
        R_Result<R_Pager<TbPost>> result = new R_Result<>();

        try {
            //String id = JWTUtils.getTokenPayload(request).getId();

            //添加查询条件
            QueryWrapper<TbPost> wrapper = new QueryWrapper<>();
            Page<TbPost> page = new Page<>(current, size, total);






            R_Pager<TbPost> data = new R_Pager<>();


            data.setCurrent(current);
            data.setSize(size);
            data.setTotal(service.count(wrapper));

            List<TbPost> records = service.page(page, wrapper).getRecords();
            records.forEach(p -> {
                System.out.println(p.getUserId());
                TbUser byId = userService.getById(p.getUserId());
                p.setUser(byId);
            });
            data.setItems(records);

            result.setData(data);

            save = true;

        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }

        if (save) {
            result.setCode(200);
            result.setMsg("成功");
        } else {
            result.setCode(250);
            result.setMsg("失败");
        }
        return result;
    }
    @GetMapping("/getListSearch/{current}/{size}/{total}/{search}")
    @ApiOperation(value = " 获取列表数据")
    @ResponseBody
    public R_Result<R_Pager<TbPost>> getTbPostSearch(HttpServletRequest request, @PathVariable Integer current, @PathVariable Integer size, @PathVariable Integer total,@PathVariable String search) {

        boolean save = false;
        R_Result<R_Pager<TbPost>> result = new R_Result<>();

        try {
            //String id = JWTUtils.getTokenPayload(request).getId();

            //添加查询条件
            QueryWrapper<TbPost> wrapper = new QueryWrapper<>();
            Page<TbPost> page = new Page<>(current, size, total);

            if (!StringUtils.isEmpty(search)) {
                wrapper.like("title", search);
            }



            R_Pager<TbPost> data = new R_Pager<>();


            data.setCurrent(current);
            data.setSize(size);
            data.setTotal(service.count(wrapper));

            List<TbPost> records = service.page(page, wrapper).getRecords();
            records.forEach(p -> {
                System.out.println(p.getUserId());
                TbUser byId = userService.getById(p.getUserId());
                p.setUser(byId);
            });
            data.setItems(records);

            result.setData(data);

            save = true;

        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }

        if (save) {
            result.setCode(200);
            result.setMsg("成功");
        } else {
            result.setCode(250);
            result.setMsg("失败");
        }
        return result;
    }

    @GetMapping("/getList/{userId}/{current}/{size}/{total}")
    @ApiOperation(value = " 获取列表数据")
    @ResponseBody
    public R_Result<R_Pager<TbPost>> addTbPost(HttpServletRequest request, @PathVariable Long userId, @PathVariable Integer current,
                                               @PathVariable Integer size, @PathVariable Integer total ) {

        boolean save = false;
        R_Result<R_Pager<TbPost>> result = new R_Result<>();

        try {
            //String id = JWTUtils.getTokenPayload(request).getId();

            //添加查询条件
            QueryWrapper<TbPost> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId);

            Page<TbPost> page = new Page<>(current, size, total);

            R_Pager<TbPost> data = new R_Pager<>();


            data.setCurrent(current);
            data.setSize(size);
            data.setTotal(service.count(wrapper));

            List<TbPost> records = service.page(page, wrapper).getRecords();
            records.forEach(p -> {
                System.out.println(p.getUserId());
                TbUser byId = userService.getById(p.getUserId());
                p.setUser(byId);
            });
            data.setItems(records);

            result.setData(data);

            save = true;

        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }

        if (save) {
            result.setCode(200);
            result.setMsg("成功");
        } else {
            result.setCode(250);
            result.setMsg("失败");
        }
        return result;

    }


    @GetMapping("/add")
    @ApiOperation(value = "TT 添加数据")
    @ResponseBody
    public R_Result<Boolean> addTbPost(HttpServletRequest request, @RequestBody TbPost dto) {

        boolean save = false;
        R_Result<Boolean> result = new R_Result<>();

        //TbPost obj = new TbPost();
        try {
            //String id = JWTUtils.getTokenPayload(request).getId();

            // plansGroup.setName(name);

            //plansGroup.setUserId(Long.valueOf(id));

            //plansGroup.setAdminId(admin_id);

            save = service.save(dto);

        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }

        if (save) {
            result.setCode(200);
            result.setMsg("成功");
        } else {
            result.setCode(250);
            result.setMsg("失败");
        }
        result.setData(save);
        return result;
    }


    @GetMapping("/edit")
    @ApiOperation(value = "TT 编辑数据")
    @ResponseBody
    public R_Result<Boolean> editTbPost(HttpServletRequest request, @RequestBody TbPost otd) {

        boolean save = false;
        R_Result<Boolean> result = new R_Result<>();
        try {

//            String userid = JWTUtils.getTokenPayload(request).getId();

            UpdateWrapper<TbPost> wrapper = new UpdateWrapper<>();

//            wrapper.eq("user_id", userid);
            wrapper.eq("id", otd.getId());
            //设置更新value
//            wrapper.set("name", name);


            save = service.update(otd, wrapper);

        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }

        if (save) {
            result.setCode(200);
            result.setMsg("成功");
        } else {
            result.setCode(250);
            result.setMsg("失败");
        }
        result.setData(save);
        return result;
    }


    @DeleteMapping("/del/{id}")
    @ApiOperation(value = "TT  条件删除数据")
    @ResponseBody
    public R_Result<Boolean> delByTbPost(HttpServletRequest request, @PathVariable Long id) {


        boolean save = false;
        R_Result<Boolean> result = new R_Result<>();

        try {
//            String userid = JWTUtils.getTokenPayload(request).getId();
            QueryWrapper<TbPost> wrapper = new QueryWrapper<>();
            //wrapper.eq("user_id", userid);
            wrapper.eq("id", id);

            save = service.remove(wrapper);

        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }

        if (save) {
            result.setCode(200);
            result.setMsg("成功");
        } else {
            result.setCode(250);
            result.setMsg("失败");
        }
        result.setData(save);
        return result;

    }
}
